package com.cyx.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyx.exam.entity.*;
import com.cyx.exam.service.*;
import com.cyx.exam.vo.ExamVO;
import com.cyx.exam.vo.OptionVO;
import com.cyx.exam.vo.QuVO;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cyx
 * @create 2021-03-17 14:24
 */
@Controller
@RequestMapping("/test")
public class TestController {
    @Resource
    private ExamService examService;

    @Resource
    private QuService quService;

    @Resource
    private QuAnswerService quAnswerService;

    @Resource
    private UserExamService userExamService;

    @Resource
    private UserBookService userBookService;

    @Resource
    private UserService userServicel;
    //展示试卷下的全部题目
    @GetMapping("/{id}")
    public String show(@PathVariable("id") Integer examId, Model model){

        List<QuVO> quVOList = new ArrayList<>();

        QueryWrapper<Qu> quWrapper = new QueryWrapper<>();
        quWrapper.eq("exam_id",examId);
        //找出题目和相应的选项，赋值给quVOList
        List<Qu> quList = quService.list(quWrapper);
        for(Qu qu : quList){
            QueryWrapper<QuAnswer> quAnswerWrapper = new QueryWrapper<>();
            quAnswerWrapper.eq("qu_id",qu.getId());
            List<QuAnswer> quAnswerList = quAnswerService.list(quAnswerWrapper);
            quVOList.add(new QuVO().setId(qu.getId())
                    .setQuType(qu.getQuType())
                    .setContent(qu.getContent())
                    .setScore(qu.getScore())
                    .setExamId(qu.getExamId())
                    .setQuAnswerList(quAnswerList));
        }
        model.addAttribute("quVOList",quVOList);
        model.addAttribute("examId",examId);
        return "exam/test";
    }

    //提交答案
    //对题目进行新增操作
    @PostMapping("/submit")
    @ResponseBody
    @Transactional
    public Result submit(@RequestBody ExamVO examVO){
        int getScore = 0;
        UserExam userExam = new UserExam();
        userExam.setName(examVO.getName())
                .setExamId(examVO.getExamId());
        //存入答题记录
        userExamService.save(userExam);
        Integer userExamId = userExam.getId();
        //对选项进行新增或更新
        HashMap<Integer, String> hashMap = new HashMap<>();
        for (OptionVO optionVO:examVO.getQuAnswerList()){
            //找出每个题目你的选项
            Integer quId = optionVO.getQuId();
            Integer quAnswerId = optionVO.getQuAnswerId();
            if (!hashMap.containsKey(quId)){
                hashMap.put(quId, String.valueOf(quAnswerId));
            }else{
                Object v = hashMap.get(quId);
                String value = v + "," + quAnswerId;
                hashMap.put(quId,value);
            }
        }
        //将k:v传入对象，存入数据库
        for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
            //比对答案
            List<Integer> list = quAnswerService.selectRightAnswer(entry.getKey());

            //赋值
            String value = entry.getValue();
            UserBook userBook = new UserBook();
            userBook.setUserExamId(userExamId)
                    .setQuId(entry.getKey())
                    .setYourOptions(value);

            StringBuilder builder = new StringBuilder();
            String[] splits = value.split(",");
            //判断答案是否正确
            int i = 0;
            for (String split :splits){
                QuAnswer quAnswer = quAnswerService.getById(split);
                builder.append(quAnswer.getContent()).append(",");
                for (Integer id : list){
                    if(split.equals(String.valueOf(id))){
                        i++;
                        break;
                    }
                }
            }
            builder.deleteCharAt(builder.length()-1);
            userBook.setOptionContent(String.valueOf(builder));
            if(i==splits.length){
                //查看题目分数
                Qu qu = quService.getById(entry.getKey());
                Integer score = qu.getScore();
                //设置获得分数
                userBook.setScore(score);
                //修改总分
                getScore += score;
            }
            //存入答题本
            userBookService.save(userBook);
        }
        //修改答题记录获得的分数
        userExam.setScore(getScore);
        userExamService.saveOrUpdate(userExam);
        return new Result("200","/exam/list/");
    }

    //查看试卷成绩
    @GetMapping("/show/{id}/{user}")
    public String show(@PathVariable("id") Integer examId,
                        @PathVariable("user") String user,
                       Model model){
        User user1 = userServicel.getOne(new QueryWrapper<User>().lambda().eq(User::getName, user));
        //如果是管理员可以查看该试卷下全部成绩
        List<UserExam> userExamList = new ArrayList<>();
        if(user1.getRole()==1){
            userExamList = userExamService.list(new QueryWrapper<UserExam>().lambda().eq(UserExam::getExamId, examId));
        }else{
            //其他人只能看自己的成绩
            userExamList = userExamService.list(new QueryWrapper<UserExam>().lambda().eq(UserExam::getExamId, examId).eq(UserExam::getName,user));
        }
        model.addAttribute("userExamList",userExamList);
        Exam exam = examService.getById(examId);
        model.addAttribute("title",exam.getTitle());
        return "exam/show";
    }

    //查看某个人的详细做题情况
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id,Model model){
        //找到对应的试卷
        UserExam userExam = userExamService.getById(id);

        //你的选项
        List<UserBook> options = userBookService.list(new QueryWrapper<UserBook>().lambda().eq(UserBook::getUserExamId, userExam.getId()).orderByAsc(UserBook::getQuId));

        //找出题目和相应的选项
        List<QuVO> quVOList = new ArrayList<>();
        QueryWrapper<Qu> quWrapper = new QueryWrapper<>();
        quWrapper.eq("exam_id",userExam.getExamId());
        List<Qu> quList = quService.list(quWrapper);
        //赋值给quVOList
        for(Qu qu : quList){
            QueryWrapper<QuAnswer> quAnswerWrapper = new QueryWrapper<>();
            quAnswerWrapper.eq("qu_id",qu.getId());
            List<QuAnswer> quAnswerList = quAnswerService.list(quAnswerWrapper);
            quVOList.add(new QuVO().setId(qu.getId())
                    .setQuType(qu.getQuType())
                    .setContent(qu.getContent())
                    .setRemark(qu.getRemark())
                    .setAnalysis(qu.getAnalysis())
                    .setScore(qu.getScore())
                    .setExamId(qu.getExamId())
                    .setQuAnswerList(quAnswerList));
        }
        model.addAttribute("options",options);
        model.addAttribute("quVOList",quVOList);
        return "exam/detail";
    }
}
